package cn.demomaster.quickpermission

import android.Manifest
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.ClipDescription
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.util.Log
import androidx.core.content.ContextCompat
import cn.demomaster.quickpermission.dialog.DialogWindowActivity
import cn.demomaster.quickpermission.util.PermissionGroupUtil
import cn.demomaster.quickpermission.util.PreferenceManager

/**
 * 测试kotlin 语法
 */
object QuickPermission {

    const val TAG: String = "QuickPermission"
    var request: PermissionRequester? = null

    @JvmStatic
    fun with(activity: Activity): PermissionRequester.Builder {
        return PermissionRequester.Builder(activity)
    }

    @JvmStatic
    fun checkPermission(activity: Activity, permissions: List<String>): Boolean {
        return checkPermission(
            activity,
            *permissions.toTypedArray<String>()
        )
    }

    @JvmStatic
    fun checkPermission(activity: Activity, vararg permissions: String): Boolean {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true
        }
        for (permission in permissions) {
            if (!checkPermission2(activity, permission)) {
                return false
            }
        }
        return true
    }

    private fun checkPermission2(activity: Activity, permissionName: String): Boolean {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { // 当手机系统大于 23 时，才有必要去判断权限是否获取
            return true
        }
        val isRegisted = isInAndroidManifest(
            activity,
            permissionName
        )
        if (!isRegisted) {
            Log.e(TAG, "[$permissionName]权限未在AndroidManifest注册")
            return false
        }
        when (permissionName) {
            Manifest.permission.REQUEST_INSTALL_PACKAGES, Manifest.permission.INSTALL_PACKAGES -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                return activity.packageManager.canRequestPackageInstalls()
            }

            Manifest.permission.SYSTEM_ALERT_WINDOW -> return Settings.canDrawOverlays(
                activity
            )

            Manifest.permission.PACKAGE_USAGE_STATS -> return PermissionGroupUtil.isGrantedUsagePremission(
                activity
            )

            Manifest.permission.WRITE_SETTINGS, Manifest.permission.WRITE_SECURE_SETTINGS -> return Settings.System.canWrite(
                activity
            )

            Manifest.permission.BIND_ACCESSIBILITY_SERVICE -> return PermissionGroupUtil.checkAndEnableAccessibilityService(
                activity
            )

            Manifest.permission.MANAGE_EXTERNAL_STORAGE -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                //boolean hasAnyRequestedLegacyExternalStorage =
                /*PackageManager pm = context.getPackageManager();
                        PackageInfo packageInfo = pm.getPackageArchiveInfo("",0);
                        context.getApplicationContext().getApplicationInfo().hasRequestedLegacyExternalStorage();*/
                //context.getApplicationContext()..getApplicationInfo(). requestLegacyExternalStorage
                val p = Environment.isExternalStorageManager()
                return p // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            } else {
                return true
            }

            Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                val p = Environment.isExternalStorageManager()
                Log.v(TAG, permissionName + "权限:" + p)
                return p // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            } else {
                val r = ContextCompat.checkSelfPermission(
                    activity,
                    permissionName
                )
                Log.v(TAG, "[" + permissionName + "]权限:" + r);
                return (r == PackageManager.PERMISSION_GRANTED) // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            }

            else -> {
                val r = ContextCompat.checkSelfPermission(
                    activity,
                    permissionName
                )
                var result = (r == PackageManager.PERMISSION_GRANTED)
                if (result) {//授权成功的要移除权限黑名单
                    PreferenceManager.onPermissionGranted(activity, permissionName)
                    PreferenceManager.setPermissionRequested(activity, permissionName, false)
                }
                //Log.v(TAG, "[" + permissionName + "]权限:" + (r == PackageManager.PERMISSION_GRANTED ? "已授权" : "未授权"));
                return result // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            }
        }
        return true
    }

    private fun isInAndroidManifest(context: Context, permissionName: String): Boolean {
        if (permissionName == Manifest.permission.BIND_ACCESSIBILITY_SERVICE) {
            return true
        }
        val pm = context.packageManager
        var pack: PackageInfo? = null
        try {
            pack = pm.getPackageInfo(context.packageName, PackageManager.GET_PERMISSIONS)
            val permissionStrings = pack.requestedPermissions
            if (permissionStrings != null) {
                for (str in permissionStrings) {
                    //Log.e(TAG, "permissionName:" + str+","+permissionName);
                    if (str.equals(permissionName, ignoreCase = true)) {
                        return true
                    }
                }
            }
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return false
    }

    @JvmStatic
    fun onRequestPermissionsResult(
        activity: Activity,
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        request?.onRequestPermissionsResult(activity, requestCode, permissions, grantResults)
    }

    @JvmStatic
    fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int, data: Intent?) {
        println("权限申请结果1:$requestCode,resultCode=$resultCode")
        request?.onActivityResult(activity, requestCode, resultCode, data)
    }


    /**
     * 启动新的 Activity 以引导用户手动授予权限。
     *
     * @param context      应用上下文
     * @param request      权限请求对象
     */
    @JvmStatic
    fun startPermissionActivity(context: Context, permissionName: String, requestCode: Int) {
        var intent: Intent? = null

        var packageURI = Uri.parse("package:" + context.packageName)
        when (permissionName) {
            Manifest.permission.WRITE_SETTINGS -> {
                intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS)
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }

            Manifest.permission.PACKAGE_USAGE_STATS -> intent =
                Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS)

            Manifest.permission.REQUEST_INSTALL_PACKAGES, Manifest.permission.INSTALL_PACKAGES -> intent =
                Intent(
                    Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES
                )

            Manifest.permission.SYSTEM_ALERT_WINDOW -> intent =
                Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)

            Manifest.permission.BIND_ACCESSIBILITY_SERVICE -> {
                intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
                //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                packageURI = null
            }

            Manifest.permission.MANAGE_EXTERNAL_STORAGE -> intent =
                Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
        }
        if (packageURI != null) {
            intent!!.setData(packageURI)
        }
        if (context is Activity) {
            context.startActivityForResult(
                intent,
                requestCode
            ) //QuickPermission.REQUEST_PERMISS_SPECIAL_CODE);
        } else {
            intent!!.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(intent)
        }
        onStartPermissionActivity(context, permissionName)
    }

    @JvmStatic
    fun onStartPermissionActivity(context: Context, permissionName: String) {
        if (permissionName == Manifest.permission.SYSTEM_ALERT_WINDOW || permissionName == Manifest.permission.BIND_ACCESSIBILITY_SERVICE) {
            val handler = Handler(Looper.getMainLooper())
            handler.post {
                val intent = Intent(context, DialogWindowActivity::class.java)
                val bundle = Bundle()
                bundle.putString("permission", permissionName)
                intent.putExtras(bundle)
                if (context !is Activity) {
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                }
                context.startActivity(intent)
                // 参数1：SecondActivity进场动画，参数2：MainActivity出场动画
                if (context is Activity) {
                    context.overridePendingTransition(0, 0)
                }
            }
        }
    }
    @JvmStatic
    fun requestClipBoardPermission(context: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            if (clipboard != null && clipboard.hasPrimaryClip()
                && clipboard.primaryClipDescription!!.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)
            ) {
                // 已经获取了粘贴板权限
            } else {
                // 未获取粘贴板权限
                QuickPermission2.setClipBoardPermission(context)
            }
        } else {
            // Android 版本低于 6.0，无需判断权限
        }
    }
    @JvmStatic
    fun setClipBoardPermission(context: Context) {
        var MIUI_VERSION_CODE = 0

        try {
            MIUI_VERSION_CODE = Build.VERSION.INCREMENTAL.toInt()
        } catch (var7: NumberFormatException) {
            var7.printStackTrace()
        }

        val intent: Intent
        if (MIUI_VERSION_CODE >= 7) {
            intent = Intent("miui.intent.action.APP_PERM_EDITOR")
            intent.setClassName(
                "com.miui.securitycenter",
                "com.miui.permcenter.permissions.AppPermissionsEditorActivity"
            )
            intent.putExtra("extra_pkgname", context.packageName)

            try {
                context.startActivity(intent)
            } catch (var6: ActivityNotFoundException) {
                var6.printStackTrace()
            }
        } else {
            intent = Intent("android.settings.APPLICATION_DETAILS_SETTINGS")
            val uri = Uri.fromParts("package", context.packageName, null as String?)
            intent.setData(uri)

            try {
                context.startActivity(intent)
            } catch (var5: ActivityNotFoundException) {
                var5.printStackTrace()
            }
        }
    }
}